package studio.raptor.dispatcher.server.listeners;

import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import studio.raptor.cmdb.ConfigFile;
import studio.raptor.cmdb.ConfigService;
import studio.raptor.cmdb.core.enums.ConfigFileFormat;

/**
 * 初始化hub配置，从配置中心获取hub的配置，加载到@Environment 中
 *
 * @author jack
 * @since 1.0
 */
public class DispatcherPreparedListener implements
    ApplicationListener<ApplicationEnvironmentPreparedEvent> {

  private static final Logger log = LoggerFactory.getLogger(DispatcherPreparedListener.class);

  public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigFile connectionConfig = ConfigService
        .getConfigFile("connection", ConfigFileFormat.Properties);
    ConfigFile proxyConfig = ConfigService.getConfigFile("proxy", ConfigFileFormat.Properties);
    ConfigFile applicationConfig = ConfigService
        .getConfigFile("application", ConfigFileFormat.Properties);

    Properties connectionProperties = parsePropertiesString(connectionConfig.getContent(),
        "connection.properties");
    Properties proxyProperties = parsePropertiesString(proxyConfig.getContent(),
        "proxy.properties");
    Properties applicationProperties = parsePropertiesString(applicationConfig.getContent(),
        "application.properties");

    log.debug("connection config:{}", connectionConfig.toString());
    log.debug("proxy config:{}", proxyProperties.toString());
    log.debug("application config:{}", applicationProperties.toString());

    ConfigurableEnvironment envi = event.getEnvironment();
    MutablePropertySources mps = envi.getPropertySources();
    if (mps != null) {
      mps.addFirst(new PropertiesPropertySource("connection", connectionProperties));
      mps.addFirst(new PropertiesPropertySource("proxy", proxyProperties));
      mps.addFirst(new PropertiesPropertySource("application", applicationProperties));
    }

  }

  private Properties parsePropertiesString(String config, String file) {
    Preconditions.checkArgument(config != null, "the config [" + file + "] is empty or not exists");
    final Properties p = new Properties();
    try {
      p.load(new StringReader(config));
    } catch (IOException e) {
      log.error("parsePropertiesString error:", e);
    }
    return p;
  }

}
